package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"shuqi-novel/models/mysql"
	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelUpdateLogic {
	return &NovelUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelUpdateLogic) NovelUpdate(in *shuqirpc.NovelUpdateRequest) (*shuqirpc.NovelUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var novel mysql.Novel
	mysql.DB.Debug().Where("id = ?", in.Id).Find(&novel)

	if novel.UserId != int(in.UserId) {
		return nil, fmt.Errorf("没有权限")
	}

	novel = mysql.Novel{
		Model: gorm.Model{
			ID: novel.ID,
		},
		Title:  in.Title,
		Author: in.Author,
		Info:   in.Info,
	}
	err := mysql.DB.Debug().Updates(&novel).Error
	if err != nil {
		return nil, fmt.Errorf("小说更新失败")
	}

	return &shuqirpc.NovelUpdateResponse{Id: int64(novel.ID)}, nil
}
